<!--
 * @Description  :
 * @Autor        : guoxi
 * @Date         : 2022-06-16 10:16:50
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2022-09-05 14:50:03
 * @FilePath     : \rpms\src\views\project\build\detail\index.vue
-->
<template>
  <el-card>
    <div class="card-wrap">
      <el-page-header content="添加可研性研究信息" @back="handleBack" />
      <div
        v-if="
          model.formData.fsbSaveStatus !== '7' && route.query.mode !== 'look'
        "
      >
        <el-button @click="goBack">取消</el-button>
        <template v-if="!isApproval">
          <el-button
            v-if="!route.query.instanceId"
            type="primary"
            :loading="model.saveLoading"
            @click="handleSave"
            >保存</el-button
          >
          <el-button
            type="primary"
            :loading="model.saveLoading"
            @click="handleSubmit"
            >提交</el-button
          >
        </template>
      </div>
    </div>
  </el-card>
  <br />

  <el-form
    :model="model.formData"
    :disabled="isApproval"
    ref="formRef"
    @submit.prevent
    :rules="formRules"
    label-width="140px"
  >
    <el-card>
      <template #header>
        <div class="card-box-header">
          <span>项目基本信息</span>
          <div v-if="show1" @click="show1 = !show1" class="header-btn">
            收起
            <i class="el-icon-arrow-down"></i>
          </div>
          <div v-else @click="show1 = !show1" class="header-btn">
            展开
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </template>
      <div v-show="show1">
        <Descriptions :projectInfo="projectInfo" />
      </div>
    </el-card>
    <br />

    <el-card>
      <template #header>
        <div class="card-box-header">
          <span>可行性研究</span>
          <div v-if="show2" @click="show2 = !show2" class="header-btn">
            收起
            <i class="el-icon-arrow-down"></i>
          </div>
          <div v-else @click="show2 = !show2" class="header-btn">
            展开
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </template>
      <div v-show="show2">
        <el-row>
          <el-col>
            <el-form-item label="关键结论" prop="keyConclusion">
              <el-input
                type="textarea"
                v-model="model.formData.keyConclusion"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="可行性研究报告" prop="fsbStudyAttachmentArr">
              <ecm-upload
                :files="model.recordDefaultFileList"
                :docid="model.docid"
                @setFile="handleRecordSuccess"
              ></ecm-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="备注">
              <el-input type="textarea" v-model="model.formData.remark" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <br />
    <el-card v-if="route.query.instanceId">
      <template #header>
        <div class="card-box-header">
          <span> 流程状态</span>
          <div v-if="show5" @click="show5 = !show5" class="header-btn">
            收起
            <i class="el-icon-arrow-down"></i>
          </div>
          <div v-else @click="show5 = !show5" class="header-btn">
            展开
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </template>
      <div v-if="steps && steps.length">
        <el-collapse-transition>
          <status-info
            :currentStep="currentStep"
            :steps="steps"
            :isSkip="isSkipLx"
          />
        </el-collapse-transition>
      </div>
    </el-card>
    <br />
    <el-card v-if="route.query.instanceId">
      <template #header>
        <div class="card-box-header">
          <span> 流转记录</span>
          <div v-if="show6" @click="show6 = !show6" class="header-btn">
            收起
            <i class="el-icon-arrow-down"></i>
          </div>
          <div v-else @click="show6 = !show6" class="header-btn">
            展开
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </template>
      <div v-show="show6">
        <el-collapse-transition>
          <approval-info :activities="approveRecord" />
        </el-collapse-transition>
      </div>
    </el-card>
  </el-form>
  <approveDialog
    v-if="approveDialogVisiable"
    :nodeId="nodeId"
    :flowType="model.flowType"
    @cancel="cancel"
    @sure="sureSubmit"
  ></approveDialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import approveDialog from "/@/components/approveDialog/index.vue";
import Descriptions from "../../detail/components/BasicsInfo.vue";
import StatusInfo from "/@/components/StatusInfo/index.vue";
import ApprovalInfo from "/@/components/ApprovalInfo/index.vue";
import {
  getProjectInfo,
  updateFsbStudy,
  getFsbStudyDetail,
  submitFsbStudy,
  getApproveHistory,
  flowSubmit
} from "/@/api/project";
import { cloneDeep } from "lodash-es";
import NotifMessage from "/@/utils/message/notification";
import { flowTypeCode } from "../../create/types";
import { flowStatusObj } from "/@/components/StatusInfo/type";
import { storageLocal } from "/@/utils/storage";
import EcmUpload from "/@/components/ecmUpload/index.vue";
// import { ElMessageBox } from "element-plus";
const router = useRouter();
const route = useRoute();
let approveDialogVisiable = ref<boolean>(false); // 点击提交弹窗，选择下一步审批人
const nodeId = route.query.nodeId ? route.query.nodeId : "ACT_010";
const formRef = ref<HTMLFormElement | null>(null) as any;
let show1 = ref<boolean>(true);
let show2 = ref<boolean>(true);
let show5 = ref<boolean>(true);
let show6 = ref<boolean>(true);
const steps = ref([]);
const approveRecord = ref([]);
const currentStep = ref(null);
const formRules = ref({
  keyConclusion: [
    { required: true, message: "请输入关键结论", trigger: "blur" }
  ],

  fsbStudyAttachmentArr: [
    { required: true, message: "请上传附件", trigger: "change" }
  ]
});
const model = reactive({
  docid: window["ecmDocType"].project,
  flowType: "",
  saveLoading: false,
  opinions2: [
    { key: "0", label: "同意" },
    { key: "1", label: "不同意" }
  ],
  opinions3: [
    { key: "0", label: "同意立项" },
    { key: "1", label: "不同意立项" },
    { key: "2", label: "有条件同意立项" }
  ],
  opinions: [
    { key: "0", label: "同意" },
    { key: "1", label: "不同意" }
    // { key: "2", label: "有条件同意" }
  ],
  defaultFileList: [],
  reportDefaultFileList: [],
  recordDefaultFileList: [],
  reviewDefaultFileList: [],
  approvalDefaultFileList: [],
  formData: {
    keyConclusion: "",
    fsbStudyAttachmentArr: [],
    remark: ""
  }
});
const flowStartData = reactive({
  formBaseInfo: {
    billName: "",
    projectName: "",
    projectManageId: -1,
    id: route.query.id,
    flowStartAttachmentArr: []
  },
  flowFormData: {
    businessId: route.query.id,
    flowTypeCode: "",
    nodeId: route.query.nodeId,
    projectManageId: -1,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "1", //立项：2，变更：20，验收：4
    flowType: "",
    assignee: null,
    opinion: ""
  }
});

const handleRecordSuccess = res => {
  model.recordDefaultFileList = res.file;
  model.formData.fsbStudyAttachmentArr = res.file;
};

const getStep = () => {
  const nodeId = route.query.nodeId ? route.query.nodeId : "ACT_010";
  steps.value = flowStatusObj[model.flowType];
  if (steps.value && steps.value.length) {
    steps.value.forEach((item, index) => {
      if (item.nodeId === nodeId) {
        currentStep.value = Number(index);
      }
    });
  }
};

const getApproveHistoryList = async () => {
  const instanceId = route.query.instanceId;
  if (instanceId) {
    const { code, data } = await getApproveHistory(instanceId);
    if (code === 200) {
      approveRecord.value = data;
    }
  }
};

const handleBack = () => {
  router.replace("/project/feasibility");
};

let projectInfo = ref(null);

const goBack = (): void => {
  router.push("/project/feasibility");
};

const handleSubmit = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (!isValid) {
    NotifMessage.warning("请补充必填信息后，再次操作！");
    return
  }
  approveDialogVisiable.value = true;
};

const flowStart = async params => {
  flowStartData.flowFormData.remarks = model.formData.remark;
  flowStartData.formSubMap.assignee = params?.handlederId?.id;
  flowStartData.formSubMap.opinion = ``;
  // flowStartData.formSubMap.opinion = JSON.stringify([
  //   {
  //     name: "关键结论",
  //     content: model.formData.keyConclusion,
  //     type: "textarea"
  //   },
  //   {
  //     name: "附件",
  //     content: model.formData.fsbStudyAttachmentArr,
  //     type: "files"
  //   },
  //   { name: "备注", content: model.formData.remark, type: "textarea" }
  // ]);

  const { code, message } = await submitFsbStudy(flowStartData);
  model.saveLoading = false;
  if (code === 200) {
    NotifMessage.success(message);
    goBack();
  } else {
    NotifMessage.error(message);
  }
};
const flowPassData = reactive({
  formBaseInfo: {
    id: route.query.id,
    acceptUsers: null
  },
  flowFormData: {
    approvalComments: "",
    approvalResult: "",
    businessId: route.query.id,
    flowId: route.query.flowId,
    flowTypeCode: "",
    instanceId: route.query.instanceId,
    nodeId: route.query.nodeId,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "1",
    flowType: "",
    nodeId: route.query.nodeId,
    procInstId: route.query.instanceId,
    taskId: route.query.taskId,
    opinion: "",
    assignee: null,
    isChargehand: "1", //1：向下提交到下一步：0：回退到某一步
    specialReject: "0"
  },
  tmpStorage: {
    nodeId: route.query.nodeId,
    flowId: route.query.flowId,
    taskId: route.query.taskId,
    handlerId: null,
    valueJson: ""
  }
});

const flowPassSubmit = async params => {
  flowPassData.flowFormData.approvalComments = params.remark;
  flowPassData.flowFormData.approvalResult = "1"; //同意：1，不同意：0
  flowPassData.flowFormData.remarks = params.remark;
  flowPassData.flowFormData.flowTypeCode = model.flowType;
  flowPassData.formSubMap.opinion = ``;
  flowPassData.tmpStorage.valueJson = JSON.stringify(flowPassData.formSubMap);
  const info = storageLocal.getItem("rdms-info");
  const userId = info?.userId;
  flowPassData.tmpStorage.handlerId = userId;
  flowPassData.formBaseInfo.acceptUsers = params?.handlederId?.id || userId;
  flowPassData.formSubMap.assignee = params?.handlederId?.id || userId;
  flowPassData.formSubMap.isChargehand = "1";
  flowPassData.formSubMap.flowType = model.flowType;
  const { code, message } = await flowSubmit(flowPassData);
  if (code === 200) {
    NotifMessage.success(message);
    router.push("/approval/todo");
  } else {
    NotifMessage.error(message);
  }
};

// 点击弹窗的确定后，保存、提交，单据往下流转
const sureSubmit = async params => {
  console.log("params", params);
  approveDialogVisiable.value = false;

  //开始流程
  const flag = await handleSave(false, "1", "2");
  if (!flag) {
    model.saveLoading = true;
    if (route.query.instanceId) {
      flowPassSubmit(params);
    } else {
      flowStart(params);
    }
  }
};

const handleSave = async (
  flag = true,
  fsbApproveStatus = "0",
  fsbSaveStatus = "1"
): Promise<any> => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (isValid) {
    try {
      model.saveLoading = true;
      const copyFormData = cloneDeep(model.formData);
      copyFormData["fsbStudyAttachment"] = JSON.stringify(
        model.formData.fsbStudyAttachmentArr
      );
      copyFormData["fsbApproveStatus"] = fsbApproveStatus;
      copyFormData["fsbSaveStatus"] = fsbSaveStatus;

      const { code, message } = await updateFsbStudy(copyFormData);
      if (code === 200) {
        if (flag) {
          model.saveLoading = false;
          NotifMessage.success(message);
          goBack();
          return true;
        } else {
          return false;
        }
      }
    } catch (err) {
      return true;
    }
  } else {
    NotifMessage.warning("请补充必填信息后，再次操作！");
    return true;
  }
};

const cancel = async () => {
  approveDialogVisiable.value = false;
  model.saveLoading = false;
};

const initProjectInfo = async () => {
  try {
    const queryId = route.query?.id ?? "";
    const projectId = route.query.projectId;
    const { code, data } = await getProjectInfo({ id: projectId });
    if (code === 200) {
      projectInfo.value = data;
      const emyp = "5," + data.approveTypeMinCode;
      model.flowType = flowTypeCode[emyp];
      flowStartData.formBaseInfo.billName =
        data.projectName + "-可行性研究-审批流程";
      flowStartData.formBaseInfo.projectName = data.projectName;
      flowStartData.formBaseInfo.projectManageId = +projectId;
      flowStartData.flowFormData.flowTypeCode = model.flowType;
      flowStartData.flowFormData.projectManageId = +projectId;
      flowStartData.formSubMap.flowType = model.flowType;
      getStep();
    }
    const res = await getFsbStudyDetail({ id: queryId });
    if (res.code === 200 && res.data != null) {
      model.formData = res.data;

      if (model.formData.fsbStudyAttachmentArr) {
        model.recordDefaultFileList = model.formData.fsbStudyAttachmentArr;
        model.recordDefaultFileList.map(el => {
          el["name"] = el.fileName;
        });
      }

      console.log(res.data, "data");
    }
  } catch (err) {
    console.log(err);
  }
};
const isApproval =
  route.query.mode === "approval" || route.query.mode === "look" ? true : false;
initProjectInfo();
// if (route.query.mode === "look") {
getApproveHistoryList();
// model.isLook = true;
// }
</script>

<style lang="scss" scoped>
.empt-content {
  height: calc(100vh - 200px);
  width: 100%;
}

.card-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-box-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-btn {
    font-size: 14px;
    cursor: pointer;
  }
}
</style>
